import './static/css/style.css'
import "@babel/polyfill"
import hplus from './static/js/hplus'
import contabs from './static/js/contabs'
import { ajax } from './jqxt/ajax'
import { postMessage, receiveMessage } from './jqxt/win'

const openers = {}

async function getData() {
    let [user, menu, message, notify] = await ajax([
        {
            url: 'https://www.easy-mock.com/mock/5d1d993e50819545155034ba/jqxt/user/1',
        },
        {
            url: 'https://www.easy-mock.com/mock/5d1d993e50819545155034ba/jqxt/menu',
        },
        {
            url: 'https://www.easy-mock.com/mock/5d1d993e50819545155034ba/jqxt/message',
        },
        {
            url: 'https://www.easy-mock.com/mock/5d1d993e50819545155034ba/jqxt/notify',
        }])
    setUser(user)
    setMenu(menu)
    setMessage(message)
    setNotify(notify)
}

// 用户信息
const setUser = result => {
    $('#span_name').html(result.data.name)
    $('#span_role').html(result.data.role)
    $('.img_profile').removeClass('hidden').prop('src', Mock.mock(`@dataImage("64x64", "${result.data.name.split('')[0]}")`))
}

// 菜单
const setMenu = result => {
    result.data = [{
        "icon": "fa fa-edit",
        "title": "跨域一级菜单a",
        "url": "http://localhost:8889/page/a.html"
    }, {
        "icon": "fa fa-refresh",
        "title": "同域一级菜单b",
        "url": "/page/b.html"
    }].concat(result.data)
    createMenus(1, result.data, $('#side-menu'))
}

// 创建菜单
const createMenus = (menu_level, menus, ul) => {
    for (let menu of menus) {
        const li = $('<li></li>')
        const a = $('<a></a>')
        // icon
        if (menu.icon) {
            a.append($(`<i class="${menu.icon}"></i>`))
        }
        // title
        if (menu_level === 1) {
            a.append($(`<span class="nav-label">${menu.title}</span>`))
        } else {
            a.append($(`<span>${menu.title}</span>`))
        }
        li.append(a)
        // 1，2级菜单有子菜单的，需要处理子菜单
        if ((menu_level === 1 || menu_level === 2) && menu.children && menu.children.length > 0) {
            a.prop('href', '#')
            a.append($('<span class="fa arrow"></span>'))
            // 添加子菜单
            const c_ul = $('<ul></ul>')
            li.append(c_ul)
            if (menu_level === 1) {
                c_ul.addClass('nav nav-second-level')
            } else {
                c_ul.addClass('nav nav-third-level')
            }
            createMenus(menu_level + 1, menu.children, c_ul)
        } else {
            a.prop('href', menu.url || '')
            a.addClass('J_menuItem')
        }
        ul.append(li)
    }
}

// 消息
const setMessage = result => {
    $('.dropdown-messages').prev().find('span.label').html(result.data.count)
    for (let n of result.data.list) {
        const img = Mock.mock(`@dataImage("50x50", "${n.img}")`)
        const ele = $(`<li class="m-t-xs">
                    <div class="dropdown-messages-box">
                        <a href="javascript:;" class="pull-left">
                            <img alt="image" class="img-circle" src="${img}">
                        </a>
                        <div class="media-body">
                            <small class="pull-right text-navy">${n.hour}</small>
                            <strong>${n.title}</strong> ${n.content}<br>
                            <small class="text-muted">${n.time}</small>
                        </div>
                    </div>
                </li>
                <li class="divider"></li>`)
        ele.eq(0).on('click', () => {
            jqxt.openWin('/page/b.html')
        })
        $('.dropdown-messages').prepend(ele)
    }
}

// notify
const setNotify = result => {
    $('.dropdown-alerts').prev().find('span.label').html(result.data.count)
    for (let n of result.data.list) {
        const ele = $(`<li>
                    <a href="javascript:;">
                        <div>
                            <i class="${n.icon} fa-fw"></i> ${n.title}
                            <span class="pull-right text-muted small">${n.hour}</span>
                        </div>
                    </a>
                </li>
                <li class="divider"></li>`)
        ele.eq(0).on('click', () => {
            jqxt.openWin('/page/b.html')
        })
        $('.dropdown-alerts').prepend(ele)
    }
}

// 根据子页面名称查找打开的opener页面名称
const getParent = childName => {
    for (let opener in openers) {
        if (openers[opener].indexOf(childName) >= 0) {
            return opener
        }
    }
    return null
}

$(document).ready(() => {
    layui.use('layer', () => {
        // 加载数据
        getData().then(() => {
            hplus.init()
            contabs.init()
        })

        // 接收消息，跨域通信
        // 打开页面
        receiveMessage('openWin', d => {
            const page = d.data
            if (page && page.url) {
                const from = d.from
                // 延迟0.1s打开，解决在弹出窗口再打开窗口时，子窗口没加载完之前被父窗口遮挡的问题
                // 原因是点击弹出窗口链接时，会触发置顶操作，layerTop消息，导致layer.zIndex变大了，如果不延迟，这里取到的layer.zIndex是置顶之前的，所以会被遮挡。
                setTimeout(() => {
                    layer.open({
                        type: 2,
                        title: page.title || '标题',
                        maxmin: true,
                        shade: 0,
                        area: [page.width + 'px', page.height + 'px'],
                        content: page.url,
                        skin: 'hplus',
                        zIndex: (layer.zIndex || 19891014),
                        success(layero, index) {
                            if (layero.data("isload") == 1) {
                                return
                            }
                            // 置顶
                            layer.setTop(layero)
                            layero.trigger('mousedown')
                            // 替换最大化、最小化、关闭图标
                            layero.find('.layui-layer-min').addClass('fa fa-minus').html('')
                            layero.find('.layui-layer-max').removeClass('layui-layer-ico').addClass('fa fa-window-maximize')
                            layero.find('.layui-layer-close').removeClass('layui-layer-ico').addClass('fa fa-close')
                            // 增加刷新页面按钮
                            const a_refresh = $('<a href="javascript:;" class="layui-layer-refresh fa fa-refresh"></a>')
                            const name = layero.find('iframe')[0]['name']
                            a_refresh.on('click', () => {
                                postMessage('refreshPage', {}, document[name])
                            })
                            layero.find('.layui-layer-setwin').prepend(a_refresh)
                            // 记录opener关系
                            if (!openers[from]) {
                                openers[from] = []
                            }
                            openers[from].push(layero.find('iframe')[0]['name'])

                            layero.data("isload", 1)
                        },
                        cancel(index, layero) {
                            // 关闭时清除opener关系
                            openers[from].pop(openers[from].indexOf(layero.find('iframe')[0]['name']))
                        },
                        full(layero) {
                            // 最大化时修改图标
                            layero.find('.layui-layer-max').removeClass('fa-window-maximize').addClass('fa-window-restore')
                        },
                        min(layero) {
                            // 最小化时修改图标
                            layero.find('.layui-layer-max').removeClass('fa-window-maximize').addClass('fa-window-restore')
                        },
                        restore(layero) {
                            // 还原时修改图标
                            layero.find('.layui-layer-max').removeClass('fa-window-restore').addClass('fa-window-maximize')
                        }
                    })
                }, 100)
            }
        })
        // 修改打开的页面标题
        receiveMessage('changeTitle', d => {
            window.layer && layer.title(d.data.title, layer.getFrameIndex(d.from))
        })
        // 窗口置顶
        receiveMessage('layerTop', d => {
            $('#layui-layer' + layer.getFrameIndex(d.from)).trigger('mousedown')
        })
        // 获取opener页面数据，通过index转发消息
        receiveMessage('getOpenerData', d => {
            const parent = getParent(d.from)
            if (parent) {
                postMessage(d.msgType, { to: d.from, data: d.data }, document[parent])
            }
        })
        // 获取opener页面数据，返回结果后通过index转发给请求的子页面
        receiveMessage('getOpenerDataRet', d => {
            if (openers[d.from].indexOf(d.data.to) >= 0) {
                postMessage(d.msgType, d.data.data, document[d.data.to])
            }
        })
        // 执行opener页面函数，通过index转发消息
        receiveMessage('execOpenerFunc', d => {
            const parent = getParent(d.from)
            if (parent) {
                postMessage(d.msgType, d.data, document[parent])
            }
        })
    })
})
